/*
 * @lc app=leetcode.cn id=567 lang=javascript
 *
 * [567] 字符串的排列
 */

// @lc code=start
/**
 * @param {string} s1
 * @param {string} s2
 * @return {boolean}
 */
var checkInclusion = function (s1, s2) {
  //两个字符串的长度
  let l1 = s1.length;
  let l2 = s2.length;
  // 两个数组用来存储字符出现次数和种类
  let origin = new Array(26).fill(0);
  let target = new Array(26).fill(0);
  // 创建窗口
  let winStart = 0;
  let winEnd = 0;
  // 统计s1中字符出现次数，以及在窗口内字符串出现的次数
  while (winEnd < l2) {
    if (winEnd < l1) {
      origin[s1.charCodeAt(winEnd) - 97]++;
      target[s2.charCodeAt(winEnd) - 97]++;
    } else {
      target[s2.charCodeAt(winStart) - 97] =
        target[s2.charCodeAt(winStart) - 97] == 0
          ? 0
          : target[s2.charCodeAt(winStart) - 97] - 1;
      target[s2.charCodeAt(winEnd) - 97]++;
      winStart++;
    }
    winEnd++;
    if (JSON.stringify(origin) == JSON.stringify(target) && winEnd >= l1) {
      return true;
    }
  }
  return false;
};
// @lc code=end
